package main.activity;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.android.volley.VolleyError;
import com.whu.zj.MyApplication;
import com.whu.zj.R;
import com.whu.zj.UIHandler;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

import datalookin.activity.ChooseActivity;
import datalookin.activity.MainWaterActivity;
import datalookin.activity.MainWaterActivity2;
import datalookin.activity.PlantMonitorActivity;
import datalookin.adapter2.ChooseAdapter;
import emergency.activity.EmergencyRecord;
import emergency.dto.AlertRecordDto;
import emergency.network.GetEmergencyRecord;
import gis.activity.MapShow;
import chat.activities.IMActivity;
import informationGet.activity.TakeInformationActivity;
import inter.Delegate;
import jubao.activity.JuBaoDeal;
import main.network.GetAllCommonType;
import main.network.GetAllWaterPlantJSON;
import main.network.GetVersion;
import remoteControl.activity.RemoteControlActivity;
import utils.CacheHelper;
import utils.PackageUtil;
import waterreview.activity.WaterReviewActivity;

/**
 * 主界面
 * Created by Administrator on 2016/3/4.
 */
public class MainActivity extends UIHandler.BaseActivity {

    Button btn_back;
    Button btn_lookin;
    Button btn_mapline;
    Button btn_notify;
    Button btn_remoteControl;
    Button btn_chat;
    Button btn_inforTake;
    Button btn_userinfo;
    Button btn_waterreview;
    Button btn_jubao;

    TextView tv_font_jubao;

    CacheHelper preferenceHelper = new CacheHelper(this);
    GetAllCommonType getAllCommonType;
    GetAllWaterPlantJSON getAllWaterPlantJSON;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initview();
        initdata();
        checkAlert();
        checkversion();
    }


    private void checkversion() {
        GetVersion getVersion = new GetVersion();
        getVersion.setDelegate(new Delegate() {
            @Override
            public void onResponse(String response) {
                double newversion = Double.parseDouble(response);
                String versionname = PackageUtil.getVersionName(MainActivity.this);
                Double version = Double.parseDouble(versionname);
                if (version < newversion) {
                    showUpdateDialog();
                }

            }

            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        getVersion.get();
    }

    //显示是否要更新的对话框
    private void showUpdateDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setIcon(android.R.drawable.ic_dialog_info);
        builder.setTitle("发现新版本");
        builder.setMessage("升级至新版app");
        builder.setCancelable(false);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                upgrade();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
            }
        });
        builder.create().show();
    }

    ProgressDialog progressDialog;
    // 升级app
    private void upgrade() {
        progressDialog = new ProgressDialog(MainActivity.this);    //进度条，在下载的时候实时更新进度，提高用户友好度
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setTitle("正在下载");
        progressDialog.setMessage("请稍候...");
        progressDialog.setMax(100);
        progressDialog.setProgress(0);
        progressDialog.setCancelable(false);
        progressDialog.show();

        UpgradThread up = new UpgradThread();
        up.setPath("http://"+getResources().getString(R.string.IP)+"/update/GetApp");
        up.start();

    }

    Delegate emergencyRecordResult = new Delegate() {
        @Override
        public void onResponse(String response) {
            if (!response.startsWith("[")) return;
            List<AlertRecordDto> alertRecordDtos = JSON.parseArray(response, AlertRecordDto.class);
            if (!alertRecordDtos.isEmpty())
            {
                EmergencyRecord.alertsStatic = alertRecordDtos;
                Intent intent = new Intent(MainActivity.this,EmergencyRecord.class);
                MainActivity.this.startActivity(intent);
            }
        }

        @Override
        public void onErrorResponse(VolleyError error) {

        }
    };
    GetEmergencyRecord getEmergencyRecord = new GetEmergencyRecord();

    {
        getEmergencyRecord.setDelegate(emergencyRecordResult);
    }
    // 检查是否有预警信息
    private void checkAlert() {
        getEmergencyRecord.get();
    }

    /**
     * 基本类型获取
     */
    Delegate allCommonType = new Delegate() {
        @Override
        public void onResponse(String response) {
            Log.i("基本类型", response);
            if (!response.startsWith("[")) return;
            preferenceHelper.putString(CacheHelper.COMMENTTYPE, "data", response);
        }

        @Override
        public void onErrorResponse(VolleyError error) {
            Toast.makeText(MainActivity.this, "获取基本类型失败", Toast.LENGTH_SHORT).show();
        }
    };

    // 基本水厂数据获取
    Delegate waterPlants = new Delegate() {
        @Override
        public void onResponse(String response) {
            Log.i("基本水厂", response);
            if (!response.startsWith("[")) return;
            preferenceHelper.putString(CacheHelper.ALLWATERPLANT, "data", response);
        }

        @Override
        public void onErrorResponse(VolleyError error) {
            Toast.makeText(MainActivity.this, "获取基本水厂失败", Toast.LENGTH_SHORT).show();
        }
    };

    private void initdata() {
        if (!preferenceHelper.contains(CacheHelper.COMMENTTYPE, "data")) {
            getCommonType();
        }

        if (!preferenceHelper.contains(CacheHelper.ALLWATERPLANT, "data")) {
            getWaterPlants();
        }

    }

    // 获取水厂数据
    private void getWaterPlants() {
        getAllWaterPlantJSON = new GetAllWaterPlantJSON();
        getAllWaterPlantJSON.setDelegate(waterPlants);
        getAllWaterPlantJSON.get();
    }

    /**
     * 请求通用数据
     */
    public void getCommonType() {
//        getAllStationnumpositionAction = new GetAllStationnumpositionAction();
//        getAllStationnumpositionAction.setDelegate(allCommonType);
//        getAllStationnumpositionAction.get();
        getAllCommonType = new GetAllCommonType();
        getAllCommonType.setDelegate(allCommonType);
        getAllCommonType.get();

    }

    View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (v == btn_back) {
                finish();
            } else if (v == btn_lookin) {
                if (MyApplication.mobileUserDto == null) {
                    Toast.makeText(MainActivity.this, "基础数据下载失败，请重新登录..", Toast.LENGTH_SHORT);
                    return;
                }
                Intent intent = null;
                if (MyApplication.mobileUserDto.getWaterUser().getWaterplantNum().endsWith("00")) {
                    intent = new Intent(MainActivity.this, ChooseActivity.class);
                } else {
                    intent = new Intent(MainActivity.this, MainWaterActivity2.class);
                    intent.putExtra("waterPlantNum", MyApplication.mobileUserDto.getWaterUser().getWaterplantNum());
                    intent.putExtra("waterPlantName", MyApplication.getRealPlant().getWaterPlantName());
                }
                MainActivity.this.startActivity(intent);
            } else if (v == btn_mapline) {
                Intent intent = new Intent(MainActivity.this, MapShow.class);
                MainActivity.this.startActivity(intent);
            } else if (v == btn_notify) {

                Intent intent = new Intent(MainActivity.this, EmergencyRecord.class);
                MainActivity.this.startActivity(intent);
            } else if (v == btn_remoteControl) {
                Intent intent = new Intent(MainActivity.this, RemoteControlActivity.class);
                MainActivity.this.startActivity(intent);
            } else if (v == btn_chat) {
                Intent intent = new Intent(MainActivity.this, IMActivity.class);
                MainActivity.this.startActivity(intent);
            } else if (v == btn_inforTake) {
                Intent intent = new Intent(MainActivity.this, TakeInformationActivity.class);
                MainActivity.this.startActivity(intent);
            } else if (v == btn_userinfo) {
                Intent intent = new Intent(MainActivity.this, MyActivity.class);
                MainActivity.this.startActivity(intent);
            }
            else if (v == btn_waterreview)
            {
                Intent intent = new Intent(MainActivity.this, WaterReviewActivity.class);
                MainActivity.this.startActivity(intent);
            }
            else if (v == btn_jubao)
            {
                Intent intent = new Intent(MainActivity.this, JuBaoDeal.class);
                MainActivity.this.startActivity(intent);
            }
        }
    };

    // 初始化界面
    private void initview() {
        btn_back = (Button) findViewById(R.id.id_btn_back);
        btn_back.setOnClickListener(onClickListener);

        btn_lookin = (Button) findViewById(R.id.id_btn_lookin);
        btn_lookin.setOnClickListener(onClickListener);
        btn_mapline = (Button) findViewById(R.id.id_btn_mapline);
        btn_mapline.setOnClickListener(onClickListener);
        btn_notify = (Button) findViewById(R.id.id_btn_notify);
        btn_notify.setOnClickListener(onClickListener);
        btn_remoteControl = (Button) findViewById(R.id.id_btn_remoteControl);
        btn_remoteControl.setOnClickListener(onClickListener);
        btn_chat = (Button) findViewById(R.id.id_btn_chat);
        btn_chat.setOnClickListener(onClickListener);

        btn_inforTake = (Button) findViewById(R.id.id_btn_inforTake);
        btn_inforTake.setOnClickListener(onClickListener);

        btn_userinfo = (Button) findViewById(R.id.id_btn_userinfo);
        btn_userinfo.setOnClickListener(onClickListener);

        btn_waterreview = (Button) findViewById(R.id.id_btn_waterreview);
        btn_waterreview.setOnClickListener(onClickListener);

        btn_jubao = (Button) findViewById(R.id.id_btn_jubao);
        btn_jubao.setOnClickListener(onClickListener);

        tv_font_jubao = (TextView) findViewById(R.id.id_font_jubao);
        tv_font_jubao.setTypeface(MyApplication.iconfont);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        if (getAllStationnumpositionAction != null)
//            getAllStationnumpositionAction.cancel();

        if (getAllWaterPlantJSON != null)
            getAllWaterPlantJSON.cancel();
        if (getAllCommonType != null)
            getAllCommonType.cancel();
    }


    // 升级线程
    private class UpgradThread extends Thread {

        String path;

        public void setPath(String path) {
            this.path = path;
        }

        @Override
        public void run() {

            InputStream in = null;
            OutputStream fileOutputStream = null;

            try {
                // 创建一个url对象
                URL url = new URL(path);
                // 通過url对象，创建一个HttpURLConnection对象（连接）
                HttpURLConnection urlConnection = (HttpURLConnection) url
                        .openConnection();
                // 通过HttpURLConnection对象，得到InputStream
                in =  urlConnection.getInputStream();
                fileOutputStream = new FileOutputStream(new File("/sdcard/weishui.apk"));
                long sum = 0;
                int num;
                byte[] buffer = new byte[1024];
                while((num = in.read(buffer))!= -1)
                {
                    fileOutputStream.write(buffer,0,num);
                    fileOutputStream.flush();
                    sum += num;
                    final long tmpsum = sum;
                    UIHandler.uiHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            progressDialog.setProgress((int)(tmpsum*100.0/(4*1024*1024)));
                        }
                    });

                }

                UIHandler.uiHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        progressDialog.dismiss();
                        update();
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (in != null) {
                        in.close();
                    }

                    if (fileOutputStream != null)
                    {
                        fileOutputStream.close();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    // 解包升级
    void update() {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(new File(Environment
                        .getExternalStorageDirectory(), "weishui.apk")),
                "application/vnd.android.package-archive");
        startActivity(intent);
    }
}
